package com.sanjin.configuration.security.provider;

import com.sanjin.service.AdminService;
import com.sanjin.service.impl.AdminDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/5/6 12:57
 */
@Component
public class AdminAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    AdminDetailsService adminDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        UserDetails userDetails = adminDetailsService.loadUserByUsername(username);
        // 判断密码是否一致
        if (userDetails != null && userDetails.getPassword().equals(password)) {
            return new UsernamePasswordAuthenticationToken(username,password,userDetails.getAuthorities());
        }
        throw new AuthenticationServiceException("admin authenticate faild");
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
